package com.sinochem.yunlian.ship.common.util;

import com.sinochem.yunlian.ship.common.constant.RedisKey;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jayway on 2017/11/22.
 */
public class MapUtil {

    public  static Map keyMap=new HashMap();
    static{
        keyMap.put(RedisKey.KEY_NODE_ALL,"所有节点");
        keyMap.put(RedisKey.KEY_PORT_ALL,"所有港口");
        keyMap.put(RedisKey.KEY_MATERIAL_CATEGORY_ALL,"所有货物");
        keyMap.put(RedisKey.KEY_MATERIAL_CATEGORY_LEVEL,"所有货物等级");
        keyMap.put(RedisKey.KEY_MATERIAL_CATEGORY_LEVEL_LIST,"货物等级：王基胜");
    }
    /**
     * 将一个 JavaBean 对象转化为一个  Map
     * @param bean 要转化的JavaBean 对象
     * @return 转化出来的  Map 对象
     * @throws IntrospectionException 如果分析类属性失败
     * @throws IllegalAccessException 如果实例化 JavaBean 失败
     * @throws InvocationTargetException 如果调用属性的 setter 方法失败
     */
    public static Map convertBean(Object bean)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result.toString());
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }


    public static Boolean hasKey(String key){
        if(keyMap.get(key)!=null){
            return true;
        }else{
            return false;
        }
    }
}
